<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              姓名：<el-input placeholder="请输入内容" v-model="selectForm.name" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              组织层级：
              <el-select v-model="selectForm.groupLevel" clearable filterable placeholder="请选择" @change="groupLevelChangeEvt">
                <el-option v-for="(item,index) in orgLevelOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              组织：
              <el-select v-model="selectForm.groupId" clearable filterable placeholder="请选择">
                <el-option v-for="(item,index) in groupOption" :key="index" :label="item.groupName" :value="item.id"></el-option>
              </el-select>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main class="zTeamTable-main-style">
          <app-table
            class="custom-td-th-style"
            :page-data="teamPageData"
            :table-columns="teamColumns"
            v-on:currentChange="teamHandleCurrentChange"
            v-on:handleCheckedRows="teamHandleCheckedRows">
          </app-table>
          <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" class="custom-dialog_style_twoLine" :before-close="cancel" :close-on-click-modal="false">
            <el-form :model="formData" :rules="rules" ref="formData" :disabled="showOnly" label-width="50%">
              <el-form-item label="姓名：" prop="formData" label-width="30%">
                <el-input v-model="formData.name" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="性别：" prop="sex" label-width="30%">
                <el-select v-model="formData.sex" clearable placeholder="请选择">
                  <el-option v-for="(item,index) in sexOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="所属组织：" prop="groupId" label-width="30%">
                <el-select v-model="formData.groupId" clearable filterable placeholder="请选择">
                  <el-option
                    v-for="(org,index) in groupOption"
                    :key="index"
                    :label="org.groupName"
                    :value="org.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="民族：" prop="nation" label-width="30%">
                <el-select v-model="formData.nation" filterable clearable placeholder="请选择">
                  <el-option v-for="(item,index) in nationOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="政治面貌：" label-width="30%">
                <el-select v-model="formData.politicsStatus" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in politicalStatusOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="证件代码：" label-width="30%">
                <el-select v-model="formData.idCardCode" filterable clearable placeholder="请选择">
                  <el-option v-for="(item,index) in credentialsCodeOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="身份证号：" prop="idCardNumber" label-width="30%">
                <el-input v-model="formData.idCardNumber" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="生日：" label-width="30%">
                <div class="block">
                  <el-date-picker
                    v-model="formData.birthday"
                    type="date"
                    value-format="timestamp"
                    format="yyyy 年 MM 月 dd 日"
                    placeholder="选择日期"
                    :picker-options="dataPickerBeforeTodayOptions">
                  </el-date-picker>
                </div>
              </el-form-item>
              <el-form-item label="专业特长：" label-width="30%">
                <el-select v-model="formData.majorArr" clearable multiple placeholder="请选择">
                  <el-option v-for="(item,index) in majorOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="学历：" label-width="30%">
                <div class="block">
                  <el-cascader
                    v-model="formData.educationArr"
                    placeholder="请选择"
                    :options="educationOption"
                    filterable
                    :props="dictProps"
                    clearable
                    change-on-select>
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="联系方式：" prop="phone" label-width="30%">
                <el-input v-model="formData.phone" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="固定电话：" label-width="30%">
                <el-input v-model="formData.telephone" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="职务：" label-width="30%">
                <el-input v-model="formData.position" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="isfooterBtnShow">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save('formData')">确 定</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import {getRegionTree} from '@/http/AppApi'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {validateIdefer, validatePhone} from '@/utils/validate'
import {createGroupDenseMember, updateGroupDenseMember, delGroupDenseMember, findGroupDenseMember, getGroupDenseMember, findGroupDefenseList} from '@/http/OrgApi'
export default {
  data () {
    return {
      dialogFormVisible: false,
      isfooterBtnShow: true,
      treeData: [],
      teamPageData: {},
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      teamColumns: [
        { prop: 'name', label: '姓名' },
        { prop: 'position', label: '职务' },
        { prop: 'phone', label: '联系电话' },
        { prop: 'groupId', label: '组织', formatter: this.groupFormatter }
      ],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      dictProps: {
        label: 'name',
        value: 'code'
      },
      selectForm: {},
      formData: {},
      orgOptions: [],
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        groupId: [
          { required: true, message: '请选择所属组织', trigger: 'blur' }
        ],
        idCardNumber: [
          { validator: validateIdefer, required: true, trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, required: true, trigger: 'blur' }
        ]
      },
      sexOption: [],
      nationOption: [],
      politicalStatusOption: [],
      credentialsCodeOption: [],
      educationOption: [],
      orgLevelOption: [],
      majorOption: [],
      groupOption: [],
      forGroupOption: []
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable
  },
  mounted () {
    getRegionTree().then(resp => {
      if (resp.code && resp.code === '200') {
        this.treeData = resp.data
      } else {
        this.$message({
          type: 'info',
          message: resp.message
        })
        return ''
      }
    })
    this.getTeamTableData()
    this.getGroupList()
    this.orgLevelOption = getDictDataOption('层级')
  },
  methods: {
    groupLevelChangeEvt (val) {
      this.getGroupList({groupLevel: val})
    },
    getGroupList (regionId) {
      findGroupDefenseList(regionId).then(resp => {
        if (resp.code && resp.code === '200') {
          this.groupOption = resp.data
          let obj = JSON.stringify(resp.data)
          if (this.forGroupOption.length === 0) {
            this.forGroupOption = JSON.parse(obj)
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    groupFormatter (row, column) {
      let groupOption = this.forGroupOption
      let resGroupName = ''
      for (let i = 0; i < groupOption.length; i++) {
        if (groupOption[i].id === row.groupId) {
          resGroupName = groupOption[i].groupName
          break
        }
      }
      return resGroupName
    },
    save (formName) {
      this.formData.education = this.formData.educationArr && this.formData.educationArr.length > 0 ? this.formData.educationArr.join(',') : ''
      this.formData.major = this.formData.majorArr && this.formData.majorArr.length > 0 ? this.formData.majorArr.join(',') : ''
      if (this.formData.id) {
        updateGroupDenseMember(this.formData).then(resp => {
          if (resp.code && resp.code === '200') {
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.getTeamTableData()
          } else {
            this.$message({
              type: 'info',
              message: resp.message
            })
          }
        })
      } else {
        createGroupDenseMember(this.formData).then(resp => {
          if (resp.code && resp.code === '200') {
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: '添加成功'
            })
            this.getTeamTableData()
          } else {
            this.$message({
              type: 'info',
              message: resp.message
            })
          }
        })
      }
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            delGroupDenseMember(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.getTeamTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
      this.currentSelectedData = []
    },
    cancel () {
      this.dialogFormVisible = false
      this.currentSelectedData = []
      this.formData = {}
    },
    getTeamTableData (param) {
      findGroupDenseMember(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.teamPageData = resp.data
          this.teamPageData.limit = 5
          if (this.teamPageData.items && this.teamPageData.items instanceof Array) {
            this.tableData = this.teamPageData.items
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    teamHandleCurrentChange (val) {
      this.selectForm.offset = (val - 1) * 10
      this.getTeamTableData(this.selectForm)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.isfooterBtnShow = callbackData.btnType !== 'get'
        this.sexOption = getDictDataOption('性别')
        this.credentialsCodeOption = getDictDataOption('证件代码')
        this.politicalStatusOption = getDictDataOption('政治面貌')
        this.nationOption = getDictDataOption('民族')
        this.educationOption = getDictDataOption('学历')
        this.majorOption = getDictDataOption('专业特长')
        if (callbackData.btnType === 'post') {
          this.dialogTitle = '新增'
          this.formData = {}
          this.showOnly = callbackData.sohwOnly
          this.dialogTitle = callbackData.dialogTitle
          this.dialogFormVisible = true
        } else {
          let m = this
          getGroupDenseMember(callbackData.rows[0].id).then(resp => {
            if (resp.code && resp.code === '200') {
              let obj = {}
              obj = JSON.stringify(resp.data)
              m.formData = JSON.parse(obj)
              let educationArr = m.formData.education !== '' && m.formData.education !== null ? m.formData.education.split(',') : []
              let majorArr = m.formData.major !== '' && m.formData.major !== null ? m.formData.major.split(',') : []
              m.$set(m.formData, 'educationArr', educationArr)
              m.$set(m.formData, 'majorArr', majorArr)
              m.showOnly = callbackData.sohwOnly
              m.dialogTitle = callbackData.dialogTitle
              m.dialogFormVisible = true
            }
          })
        }
      }
    },
    teamHandleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
      } else {
        this.currentSelectedData = []
      }
    },
    appTreeClick (data) {
      this.selectForm.regionId = data.id
      this.selectForm.offset = 0
      this.getGroupList(data.id)
      this.getTeamTableData(this.selectForm)
    },
    searchHandleClick () {
      this.selectForm.offset = 0
      this.getTeamTableData(this.selectForm)
    }
  }
}
</script>
<style scoped>
.custom-td-th-style .el-table td, .el-table th{
  padding: 2px 0;
}
.elheight .el-main::-webkit-scrollbar {
  width: 5px;
  height: 10px;
}
.elheight .el-main::-webkit-scrollbar-thumb {
  background-color: rgba(144,147,153,.3);
  border-radius: 3px;
}
</style>
